/**
 * @description 查询作品
 */

const { findOneWork, findWorkList } = require('../../service/works')
const { ErrorRes, SuccessRes } = require('../../res-model/index')
const { findOneWorkFailInfo, findOneWorkDbErrorFailInfo } = require('../../res-model/failInfo/index')

/**
 * 查询单个作品
 * @param {string} id workId
 * @param {string} author 作者 username（保证安全性，避免查询他人作品）
 */
async function findMyWork(id, author) {
  if (!id || !author) return new ErrorRes(findOneWorkFailInfo, 'id 或 author 为空')

  try {
    const work = await findOneWork({ id, author })
    if (work) {
      return new SuccessRes(work)
    }
    return new ErrorRes(findOneWorkFailInfo, 'id 或 author 不匹配')
  } catch (ex) {
    console.error('查询单个作品', ex)
    return new ErrorRes(findOneWorkDbErrorFailInfo) // 数据库错误
  }
}

/**
 * 获取自己的作品或模板
 * @param {object} queryInfo 查询条件
 * @param {object} pageInfo 分页
 */
async function findMyWorkList(queryInfo = {}) {
  const { username, title, status, isTemplate, pageIndex, pageSize } = queryInfo

  const whereOpt = {
    author: username,
    ...(title && { title: { $regex: title, $options: 'i' } }), // mongoose $regex 正则，用于实现模糊查询  $options: 'i' 忽略大小写
    ...(isTemplate && { isTemplate: !!parseInt(isTemplate) }), //isTemplate 0/1 转成 boolean
    ...(status && { status: parseInt(status) })
  }

  const pageOpt = {
    ...(pageIndex && { pageIndex: parseInt(pageIndex) }),
    ...(pageSize && { pageSize: parseInt(pageSize) })
  }
  const res = await findWorkList(whereOpt, pageOpt)
  return new SuccessRes(res)
}

module.exports = {
  findMyWork,
  findMyWorkList
}
